//
//  XTAlertViewController.swift
//  GallopFresh
//
//  Created by huang weiqiang on 2020/9/24.
//  Copyright © 2020 鲜恬科技. All rights reserved.
//

import UIKit

typealias XTAlertViewClickButtonBlock = ((_ alertView: XTAlertView,_ buttonIndex:Int)->Void)?

typealias XTAlertCallBack = (NSInteger)->()

protocol XTAlertViewDelegate {
    // Called when a button is clicked. The view will be automatically dismissed after this call returns
    func alertView(alertView:XTAlertView,clickedButtonAtIndex:Int)
}
class XTAlertView: UIView {
    var callBack: XTAlertCallBack!
    private var _clickButtonBlock:XTAlertViewClickButtonBlock!
    var contentView: UIView!
    var bkgBtnView: UIButton!
    var titleStr: String = ""
    var message: String = ""
    var lineView1: UIView!
    var msgLabel: UILabel!
    var titleLab: UILabel!
    var colorType: NSInteger = 0  //0： 取消按钮灰色 右侧按钮高亮  1: 左侧按钮高亮 右侧按钮灰色
    var msgAttrType: NSInteger = 0 //message用attri表示 0：不用attri展示  1： 切换门店时会用attri
    private var _cancelButtonTitle:String?
    private var _otherButtonTitles:[String] = []
    public var delegate : XTAlertViewDelegate?//weak
    
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        self.backgroundColor = UIColor.clear
        
        self.bkgBtnView = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        self.bkgBtnView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.65)
        self.bkgBtnView.alpha = 0
        self.bkgBtnView.addTarget(self, action: #selector(dismissAlertView), for: .touchUpInside)
        self.addSubview(self.bkgBtnView)
        
        self.contentView = UIView.init(frame: CGRect.init(x: 44, y: 280, width: kScreenWidth - 88, height: 125))
        self.contentView.backgroundColor = UIColor.white
        self.contentView.layer.cornerRadius = 10
        self.contentView.layer.masksToBounds = true
        self.bkgBtnView.addSubview(self.contentView)
        
        //标题
        self.titleLab = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: self.contentView.frame.size.width, height: 14))
        self.titleLab.backgroundColor = UIColor.clear
        self.titleLab.textAlignment = .center
        self.titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.titleLab.textColor = Theme.titleLabColor
        self.titleLab.text = self.titleStr
        self.titleLab.numberOfLines = 0
        self.contentView.addSubview(self.titleLab)
        
        //内容
        self.msgLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: self.contentView.frame.size.width - 40, height: 14))
        self.msgLabel.backgroundColor = UIColor.clear
        self.msgLabel.textAlignment = .center
        self.msgLabel.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        self.msgLabel.textColor = Theme.titleLabColor
        self.msgLabel.text = self.message
        self.msgLabel.numberOfLines = 0
        self.contentView.addSubview(self.msgLabel)
        
        ///线条
        self.lineView1 = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.contentView.frame.size.width, height: 0.5))
        self.lineView1.backgroundColor = UIColor.init(hex: 0xE1E3E6, alpha: 1)
        self.contentView.addSubview(self.lineView1)
        self.addsnpLayout()
        
    }
    
    ///赋值
    func setupDefault(){
        self.titleLab.text = self.titleStr
        self.msgLabel.text = self.message
        if self.titleStr == "" {
            self.titleLab.snp.updateConstraints { (make) in
                make.top.equalTo(self.contentView.snp.top).offset(0)
                make.height.greaterThanOrEqualTo(0)
            }
        }else{
            
            self.titleLab.snp.updateConstraints { (make) in
                make.top.equalTo(self.contentView.snp.top).offset(20)
                make.height.greaterThanOrEqualTo(14)
            }
        }
        
        if self.message == "" {
            self.msgLabel.snp.updateConstraints { (make) in
                make.top.equalTo(self.titleLab.snp.bottom).offset(0)
                make.height.equalTo(0)
            }
        }else{
            if self.msgAttrType > 0 {
                self.msgLabel.frame.size.height = 300
                self.msgLabel.numberOfLines = 0
                self.msgLabel.sizeToFit()
                let attr = NSMutableAttributedString.init(string: self.message)
                let attri = [NSAttributedStringKey.foregroundColor: Theme.mainColor]
                attr.addAttributes(attri, range: NSRange.init(location: 8, length: 4))
                attr.addAttributes(attri, range: NSRange.init(location: 13, length: 4))
                attr.addAttributes(attri, range: NSRange.init(location: 18, length: 4))
                self.msgLabel.attributedText = attr
                var tempTop: CGFloat = 23
                if self.titleStr != "" {
                    tempTop = 16
                }
                self.msgLabel.snp.updateConstraints { (make) in
                    make.height.equalTo(self.msgLabel.frame.size.height)
                    make.top.equalTo(self.titleLab.snp.bottom).offset(tempTop)

                }
            }else{
                self.msgLabel.frame.size.height = 300
                self.msgLabel.numberOfLines = 0
                self.msgLabel.sizeToFit()
                var tempH: CGFloat = XTManageCenter.getLabHeight(labelStr: self.message, font: UIFont.init(name: Theme.PingFangSCRegular, size: 14)!, width: self.contentView.frame.size.width-44)
                if tempH < 30 {
                    tempH = 30
                }
                var tempTop: CGFloat = 23
                if self.titleStr != "" {
                    tempTop = 16
                }
                if tempH > 30 {
                    //有多行的情况
                    self.msgLabel.textAlignment = .left
                }
                self.msgLabel.snp.updateConstraints { (make) in
                    make.height.equalTo(tempH)
                    make.top.equalTo(self.titleLab.snp.bottom).offset(tempTop)
                }
            }
        }
        if (self.titleStr != "" && self.message != "") {
            //有title 和 message
            self.lineView1.snp.updateConstraints { (make) in
                make.top.equalTo(self.msgLabel.snp.bottom).offset(13)
            }
        }else if (self.titleStr == "" && self.message != "") {
            //只有message
            self.lineView1.snp.updateConstraints { (make) in
                make.top.equalTo(self.msgLabel.snp.bottom).offset(28)
            }
        }else{
            self.lineView1.snp.updateConstraints { (make) in
                make.top.equalTo(self.msgLabel.snp.bottom).offset(23)
            }
        }

        if _otherButtonTitles.count == 0 {
            //说明alertView只有一个按钮
            let btn1Title = _cancelButtonTitle
            let btn1 = UIButton.init(frame: CGRect.init(x: 0, y: self.lineView1.frame.maxY, width: self.contentView.frame.size.width, height: 49))
            btn1.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
            btn1.setTitleColor(Theme.line8Color, for: .normal)
            btn1.setTitleColor(Theme.line8Color, for: .highlighted)
            btn1.setBackgroundImage(UIImage.image(withColor: Theme.whiteColor), for: .normal)
            btn1.setBackgroundImage(UIImage.image(withColor: Theme.E5Color), for: .highlighted)
            btn1.setTitle(btn1Title, for: .normal)
            btn1.setTitle(btn1Title, for: .highlighted)
            btn1.addTarget(self, action: #selector(btn1Action), for: .touchUpInside)
            self.contentView.addSubview(btn1)
            btn1.snp.makeConstraints { (make) in
                make.left.equalTo(self.contentView.snp.left).offset(0)
                make.width.equalTo(self.contentView.frame.size.width)
                make.height.equalTo(49)
                make.top.equalTo(self.lineView1.snp.bottom)
                make.bottom.equalTo(self.contentView.snp.bottom)
            }
            btn1.setTitleColor(UIColor.init(hex: 0x44B549), for: .normal)
            btn1.setTitleColor(UIColor.init(hex: 0x44B549), for: .highlighted)
        }else{
            //两个按钮的布局
            let btn1Title = _cancelButtonTitle
            let btn1 = UIButton.init(frame: CGRect.init(x: 0, y: self.lineView1.frame.maxY, width: self.contentView.frame.size.width/2-0.25, height: 49))
            btn1.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
            btn1.setTitle(btn1Title, for: .normal)
            btn1.setTitle(btn1Title, for: .highlighted)
            btn1.setBackgroundImage(UIImage.image(withColor: Theme.whiteColor), for: .normal)
            btn1.setBackgroundImage(UIImage.image(withColor: Theme.E5Color), for: .highlighted)
            btn1.addTarget(self, action: #selector(btn1Action), for: .touchUpInside)
            self.contentView.addSubview(btn1)
            
            let btn2Title = _otherButtonTitles[0]
            let btn2 = UIButton.init(frame: CGRect.init(x: btn1.frame.maxX, y: self.lineView1.frame.maxY, width: self.contentView.frame.size.width/2-0.25, height: 49))
            btn2.leftBorder(width: 0.5, borderColor: UIColor.init(hex: 0xE1E3E6, alpha: 1))
            btn2.frame = CGRect.init(x: btn1.frame.maxX, y: 0, width: self.contentView.frame.size.width/2, height: 49)
            btn2.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
            btn2.setTitleColor(Theme.mainColor, for: .normal)
            btn2.setTitleColor(Theme.mainColor, for: .highlighted)
            btn2.setTitle(btn2Title, for: .normal)
            btn2.setTitle(btn2Title, for: .highlighted)
            btn2.setBackgroundImage(UIImage.image(withColor: Theme.whiteColor), for: .normal)
            btn2.setBackgroundImage(UIImage.image(withColor: Theme.E5Color), for: .highlighted)
            btn2.addTarget(self, action: #selector(btn2Action), for: .touchUpInside)
            self.contentView.addSubview(btn2)
            
            if self.colorType == 0 {
                btn1.setTitleColor(Theme.line8Color, for: .normal)
                btn1.setTitleColor(Theme.line8Color, for: .highlighted)
                btn2.setTitleColor(Theme.mainColor, for: .normal)
                btn2.setTitleColor(Theme.mainColor, for: .highlighted)
            }else{
                btn1.setTitleColor(Theme.mainColor, for: .normal)
                btn1.setTitleColor(Theme.mainColor, for: .highlighted)
                btn2.setTitleColor(Theme.line8Color, for: .normal)
                btn2.setTitleColor(Theme.line8Color, for: .highlighted)
            }
            
            btn1.snp.makeConstraints { (make) in
                make.left.equalTo(self.contentView.snp.left).offset(0)
                make.width.equalTo(self.contentView.frame.size.width/2)
                make.height.equalTo(49)
                make.top.equalTo(self.lineView1.snp.bottom)
            }
            
            btn2.snp.makeConstraints { (make) in
                make.top.equalTo(self.lineView1.snp.bottom)
                make.left.equalTo(btn1.snp.right).offset(0)
                make.width.equalTo(self.contentView.frame.size.width/2)
                make.height.equalTo(49)
                make.bottom.equalTo(self.contentView.snp.bottom)
            }
        }
        self.updateConstraints()
    }
    
    public convenience init(title:String, message:String, delegate: XTAlertViewDelegate?,cancelButtonTitle: String?,otherButtonTitles:[String]){
        self.init()
        _cancelButtonTitle = cancelButtonTitle
        for eachObject in otherButtonTitles{
            _otherButtonTitles.append(eachObject)
        }
        self.titleStr = title
        self.message = message
    }
    
    func doSomething() {
        self.setupDefault()
    }
    
    
    // shows popup alert animated.
    open func show(){
        UIApplication.shared.keyWindow?.addSubview(self)
        self.startAnimation()
    }
    
    open class func showAttriAlertView(title:String, message:String, cancelButtonTitle:String?, otherButtonTitles:String, type: NSInteger? = nil, clickButtonBlock: XTAlertViewClickButtonBlock){
        let alertView = XTAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: [otherButtonTitles])
        alertView.msgAttrType = 1
        alertView._clickButtonBlock = clickButtonBlock
        alertView.doSomething()
        alertView.show()
    }
    
    //otherButtonTitlesArr 数组
    open class func showAlertView(title:String? = nil,
                                  message:String? = nil,
                                  cancelButtonTitle:String?=nil,
                                  otherButtonTitlesArr:[String]? = nil,
                                  type: NSInteger? = nil,
                                  clickButtonBlock: XTAlertViewClickButtonBlock? = nil){
        let alertView = XTAlertView(title: title ?? "", message: message ?? "", delegate: nil, cancelButtonTitle: cancelButtonTitle ?? "", otherButtonTitles: otherButtonTitlesArr ?? [])
        alertView._clickButtonBlock = clickButtonBlock
        alertView.doSomething()
        alertView.show()
    }
    
    ///otherButtonTitles 字符串
//    open class func showAlertView(title:String? = nil,
//                                  message:String? = nil,
//                                  cancelButtonTitle:String?,
//                                  otherButtonTitles: String? = nil,
//                                  type: NSInteger? = nil,
//                                  clickButtonBlock: XTAlertViewClickButtonBlock){
//        var tempOther = ""
//        otherButtonTitles
//        let alertView = XTAlertView(title: title ?? "", message: message ?? "", delegate: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: [otherButtonTitles])
//        alertView._clickButtonBlock = clickButtonBlock
//        alertView.doSomething()
//        alertView.show()
//    }
    
    ///hk支付弹框 颜色不一样
//    open class func showHKPayDetailAlertView(title:String? = nil,
//                                             message:String? = nil,
//                                             cancelButtonTitle:String?,
//                                             otherButtonTitles:String,
//                                             type: NSInteger? = nil,
//                                             clickButtonBlock: XTAlertViewClickButtonBlock){
//        let alertView = XTAlertView(title: title ?? "", message: message ?? "", delegate: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: [otherButtonTitles])
//        alertView.colorType = 1
//        alertView._clickButtonBlock = clickButtonBlock
//        alertView.doSomething()
//        alertView.show()
//    }
    
    
    ///hk支付弹框 颜色不一样
    open class func showHKPayDetailAlertView(title:String? = nil, message:String? = nil, cancelButtonTitle:String?, otherButtonTitles:String, clickButtonBlock: XTAlertViewClickButtonBlock){
        let alertView = XTAlertView(title: title ?? "", message: message ?? "", delegate: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: [otherButtonTitles])
        alertView.colorType = 1
        alertView._clickButtonBlock = clickButtonBlock
        alertView.doSomething()
        alertView.show()
    }
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //开始动画
    func startAnimation(){
        self.bkgBtnView.alpha = 0
        UIView.animate(withDuration: 0.24) {
            self.bkgBtnView.alpha = 1
        }
    }
    
    ///关闭
    @objc func dismissAlertView(){
        self.bkgBtnView.alpha = 1
        UIView.animate(withDuration: 0.24, animations: {
            self.bkgBtnView.alpha = 0
        }) { (flag) in
            self.removeFromSuperview()
        }
    }
    
    ///关闭按钮
    @objc func btn1Action(){
        if self.callBack != nil {
            self.callBack(0)
        }
        if let aBlock = _clickButtonBlock {
            aBlock!(self, 0)
        }
        self.dismissAlertView()
    }
    
    ///确定按钮
    @objc func btn2Action(){
        if self.callBack != nil {
            self.callBack(1)
        }
        if let aBlock = _clickButtonBlock {
            aBlock!(self, 1)
        }
        self.dismissAlertView()
    }
    
    ///布局
    func addsnpLayout() {
        self.bkgBtnView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalTo(0)
        }
        
        self.contentView.snp.makeConstraints { (make) in
            make.left.equalTo(self.bkgBtnView.snp.left).offset(44)
            make.right.equalTo(self.bkgBtnView.snp.right).offset(-44)
            make.top.equalTo(self.bkgBtnView.snp.top).offset(280)
        }
        
        self.titleLab.snp.makeConstraints { (make) in
            make.left.equalTo(self.contentView.snp.left).offset(20)
            make.right.equalTo(self.contentView.snp.right).offset(-20)
            make.top.equalTo(self.contentView.snp.top).offset(20)
            make.height.greaterThanOrEqualTo(14)
        }

        
        self.msgLabel.snp.makeConstraints { (make) in
            make.left.equalTo(self.contentView.snp.left).offset(20)
            make.right.equalTo(self.contentView.snp.right).offset(-20)
            make.top.equalTo(self.titleLab.snp.bottom).offset(16)
            make.height.equalTo(30)
        }
        
        self.lineView1.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(0.5)
            make.top.equalTo(self.msgLabel.snp.bottom).offset(12)
        }
    }
    
}

